package array

import "math"

// func abs(x int) int {
// 	if x < 0 {
// 		return -x
// 	}
// 	return x
// }

func threeSumClosest(nums []int, target int) int {

	min := math.MaxInt64
	res := 0

	length := len(nums)

	for first := 0; first < length-2; first++ {
		if first > 0 && nums[first-1] == nums[first] {
			continue
		}

		for second := first + 1; second < length; second++ {
			if second > first+1 && nums[second] == nums[second-1] {
				continue
			}

			for third := second + 1; third < length; third++ {
				sum := nums[first] + nums[second] + nums[third]
				delta := abs(sum - target)
				if delta == 0 {
					return target
				}
				if delta < min {
					min = delta
					res = sum
				}
			}
		}
	}

	return res

}

func abs(a int) int {
	if a < 0 {
		return -a
	} else {
		return a
	}
}
